package com.star.spring.websocket.component;

import com.star.spring.websocket.handler.WebSocketHandler;
import com.star.spring.websocket.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Slf4j
@Component
public class WebSocketMessageScheduler {

    @Autowired
    private WebSocketHandler webSocketHandler;

    /**
     * 每30秒发送一次心跳消息
     */
    @Scheduled(fixedRate = 30000)
    public void sendHeartbeat() {
        int connectionCount = webSocketHandler.getConnectionCount();
        if (connectionCount > 0) {
            Message heartbeatMessage = new Message();
            heartbeatMessage.setType("HEARTBEAT");
            heartbeatMessage.setContent("服务器心跳 - 当前连接数: " + connectionCount);
            heartbeatMessage.setTimestamp(System.currentTimeMillis());
            
            webSocketHandler.broadcastMessage(heartbeatMessage);
            log.info("发送心跳消息，当前连接数: {}", connectionCount);
        }
    }

    /**
     * 每60秒发送一次状态更新
     */
    @Scheduled(fixedRate = 60000)
    public void sendStatusUpdate() {
        Set<String> sessionIds = webSocketHandler.getAllSessionIds();
        if (!sessionIds.isEmpty()) {
            Message statusMessage = new Message();
            statusMessage.setType("STATUS_UPDATE");
            statusMessage.setContent("服务器状态更新");
            statusMessage.setTimestamp(System.currentTimeMillis());
            statusMessage.setData(sessionIds);
            
            webSocketHandler.broadcastMessage(statusMessage);
            log.info("发送状态更新消息，活跃会话数: {}", sessionIds.size());
        }
    }
} 